//
//  TableViewImageViewCell.m
//  DebugDemo
//
//  Created by XFB on 2019/5/22.
//  Copyright © 2019 ZhouCheng. All rights reserved.
//

#import "TableViewImageViewCell.h"
#import "FLAnimatedImage/FLAnimatedImage.h"

@interface TableViewImageViewCell ()

@property (nonatomic, strong) FLAnimatedImageView *imageView1;

@end

@implementation TableViewImageViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI
{
    self.imageView1 = [[FLAnimatedImageView alloc] init];
    self.imageView1.contentMode = UIViewContentModeScaleAspectFit;
    self.imageView1.clipsToBounds = YES;
    [self.contentView addSubview:self.imageView1];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.imageView1.frame = CGRectMake(0, 0, ScreenW, 115);
}

- (void)setImageURLString:(NSString *)imageURLString
{
    _imageURLString = imageURLString;
    NSURL *url = [NSURL URLWithString:imageURLString];
    [self loadAnimatedImageWithURL:url completion:^(FLAnimatedImage *animatedImage) {
        self.imageView1.animatedImage = animatedImage;
    }];
}

- (void)loadAnimatedImageWithURL:(NSURL *const)url
                      completion:(void (^)(FLAnimatedImage *animatedImage))completion
{
    NSString *const filename = url.lastPathComponent;
    NSString *const diskPath = [NSHomeDirectory() stringByAppendingPathComponent:filename];
    
    NSData * __block animatedImageData = [[NSFileManager defaultManager] contentsAtPath:diskPath];
    FLAnimatedImage * __block animatedImage = [[FLAnimatedImage alloc] initWithAnimatedGIFData:animatedImageData];
    
    if (animatedImage) {
        if (completion) {
            completion(animatedImage);
        }
    } else {
        [[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            animatedImageData = data;
            animatedImage = [[FLAnimatedImage alloc] initWithAnimatedGIFData:animatedImageData];
            if (animatedImage) {
                if (completion) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        completion(animatedImage);
                    });
                }
                [data writeToFile:diskPath atomically:YES];
            }
        }] resume];
    }
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
